import React, { useState } from 'react';
import { formatToBeijingTime } from '../utils/timeUtils';

const DatabaseDebugPage = () => {
  // 修改：将tableName的初始值设置为默认表名，并添加表名选项
  const tableOptions = [
    { value: '', label: '请选择表名' },
    { value: 'storage_slots', label: 'storage_slots (货位表)' },
    { value: 'TaskList', label: 'TaskList (任务列表)' },
    { value: 'goods_info', label: 'goods_info (货物信息)' },
    { value: 'tasklist_audit', label: 'tasklist_audit (任务审计)' },
  
  ];
  
  const [tableName, setTableName] = useState('');
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [selectedRows, setSelectedRows] = useState(new Set());
  // 新增状态用于无货货位查询
  const [emptySlotsData, setEmptySlotsData] = useState([]);
  const [emptySlotsLoading, setEmptySlotsLoading] = useState(false);
  const [emptySlotsError, setEmptySlotsError] = useState('');
  // 新增状态用于未下发任务查询
  const [unissuedTasksData, setUnissuedTasksData] = useState([]);
  const [unissuedTasksLoading, setUnissuedTasksLoading] = useState(false);
  const [unissuedTasksError, setUnissuedTasksError] = useState('');
  // 新增状态用于自动插入任务
  const [autoInsertLoading, setAutoInsertLoading] = useState(false);
  const [autoInsertResult, setAutoInsertResult] = useState(null);
  const [autoInsertError, setAutoInsertError] = useState('');

  const fetchTableData = async () => {
    if (!tableName) {
      setError('请选择表名');
      return;
    }

    setLoading(true);
    setError('');
    setTableData([]);
    setSelectedRows(new Set()); // 清除选中状态

    try {
      let apiUrl;
      
      // 特殊处理联表查询
      if (tableName === 'available_slots') {
        apiUrl = 'http://localhost:3001/api/slots/available';
      } else {
        // 使用新的通用API端点
        apiUrl = `http://localhost:3001/api/table/${tableName}`;
      }

      console.log(`正在请求: ${apiUrl}`);
      
      const response = await fetch(apiUrl);
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP错误: ${response.status} ${response.statusText}\n响应内容: ${errorText}`);
      }
      
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        const text = await response.text();
        console.error('收到非JSON响应:', text);
        throw new Error(`服务器返回了非JSON响应。内容类型: ${contentType || '未知'}\n响应内容: ${text.substring(0, 200)}...`);
      }
      
      const result = await response.json();
      console.log('收到响应:', result);

      if (result.success) {
        setTableData(result.data);
      } else {
        setError(result.message || '获取数据失败');
      }
    } catch (err) {
      console.error('获取数据时发生错误:', err);
      setError('获取数据时发生错误: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  // 新增：查询无货货位（不考虑任务状态）
  const fetchEmptySlots = async () => {
    setEmptySlotsLoading(true);
    setEmptySlotsError('');
    setEmptySlotsData([]);

    try {
      const apiUrl = 'http://localhost:3001/api/slots/empty';
      console.log(`正在请求无货货位: ${apiUrl}`);
      
      const response = await fetch(apiUrl);
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP错误: ${response.status} ${response.statusText}\n响应内容: ${errorText}`);
      }
      
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        const text = await response.text();
        throw new Error(`服务器返回了非JSON响应。内容类型: ${contentType || '未知'}\n响应内容: ${text.substring(0, 200)}...`);
      }
      
      const result = await response.json();
      console.log('收到无货货位响应:', result);

      if (result.success) {
        setEmptySlotsData(result.data);
      } else {
        setEmptySlotsError(result.message || '获取无货货位数据失败');
      }
    } catch (err) {
      console.error('获取无货货位时发生错误:', err);
      setEmptySlotsError('获取无货货位时发生错误: ' + err.message);
    } finally {
      setEmptySlotsLoading(false);
    }
  };

  // 新增：查询未下发任务
  const fetchUnissuedTasks = async () => {
    setUnissuedTasksLoading(true);
    setUnissuedTasksError('');
    setUnissuedTasksData([]);

    try {
      const apiUrl = 'http://localhost:3001/api/tasks/unissued';
      console.log(`正在请求未下发任务: ${apiUrl}`);
      
      const response = await fetch(apiUrl);
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP错误: ${response.status} ${response.statusText}\n响应内容: ${errorText}`);
      }
      
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        const text = await response.text();
        throw new Error(`服务器返回了非JSON响应。内容类型: ${contentType || '未知'}\n响应内容: ${text.substring(0, 200)}...`);
      }
      
      const result = await response.json();
      console.log('收到未下发任务响应:', result);

      if (result.success) {
        setUnissuedTasksData(result.data);
      } else {
        setUnissuedTasksError(result.message || '获取未下发任务数据失败');
      }
    } catch (err) {
      console.error('获取未下发任务时发生错误:', err);
      setUnissuedTasksError('获取未下发任务时发生错误: ' + err.message);
    } finally {
      setUnissuedTasksLoading(false);
    }
  };

  // 修改：自动查询无货货位（仅查询，不插入）
  const autoQueryEmptySlots = async () => {
    setAutoInsertLoading(true);
    setAutoInsertResult(null);
    setAutoInsertError('');

    try {
      const apiUrl = 'http://localhost:3001/api/tasks/auto-query-empty-slots';
      console.log(`正在请求自动查询无货货位: ${apiUrl}`);
      
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        }
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP错误: ${response.status} ${response.statusText}\n响应内容: ${errorText}`);
      }
      
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        const text = await response.text();
        throw new Error(`服务器返回了非JSON响应。内容类型: ${contentType || '未知'}\n响应内容: ${text.substring(0, 200)}...`);
      }
      
      const result = await response.json();
      console.log('收到自动查询响应:', result);

      if (result.success) {
        setAutoInsertResult(result);
        setAutoInsertError(''); // 清除错误信息
      } else {
        setAutoInsertError(result.message || '自动查询失败');
      }
    } catch (err) {
      console.error('自动查询无货货位时发生错误:', err);
      setAutoInsertError('自动查询无货货位时发生错误: ' + err.message);
    } finally {
      setAutoInsertLoading(false);
    }
  };

  // 插入指定货位任务
  const insertEmptySlotTask = async (row, column, layer) => {
    try {
      const response = await fetch('http://localhost:3001/api/tasks/empty-slot', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          Unload_Line: row,    // 使用1基索引
          Unload_Col: column,  // 使用1基索引
          Unload_Layer: layer  // 使用1基索引
        })
      });
      
      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP错误: ${response.status} ${response.statusText}\n响应内容: ${errorText}`);
      }
      
      const result = await response.json();
      console.log('插入货位任务结果:', result);
      
      if (result.success) {
        // 插入成功后刷新数据
        await fetchTableData();
        return { success: true, message: result.message };
      } else {
        return { success: false, message: result.message };
      }
    } catch (error) {
      console.error('插入货位任务失败:', error);
      return { success: false, message: '插入货位任务失败: ' + error.message };
    }
  };

  // 删除选中的记录
  const deleteSelectedRows = async () => {
    if (selectedRows.size === 0) {
      setError('请选择要删除的记录');
      return;
    }

    setLoading(true);
    setError('');

    try {
      // 获取选中行的ID
      const selectedIds = Array.from(selectedRows);
      
      // 批量删除
      const deletePromises = selectedIds.map(id => 
        fetch(`http://localhost:3001/api/tasks/${id}`, {
          method: 'DELETE'
        })
      );

      const responses = await Promise.all(deletePromises);
      
      // 检查是否有错误响应
      const hasError = responses.some(response => !response.ok);
      
      if (hasError) {
        throw new Error('部分删除操作失败');
      }

      // 删除成功后刷新数据
      await fetchTableData();
      
      // 清除选中状态
      setSelectedRows(new Set());
      
      console.log(`成功删除 ${selectedIds.length} 条记录`);
    } catch (err) {
      console.error('删除记录时发生错误:', err);
      setError('删除记录时发生错误: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  // 渲染表格数据
  const renderTableData = () => {
    if (tableData.length === 0) return null;

    // 获取列名
    const columns = Object.keys(tableData[0]);

    return (
      <div style={{ marginTop: '20px' }}>
        <h3>查询结果:</h3>
        <div style={{ marginBottom: '10px' }}>
          <button
            onClick={deleteSelectedRows}
            disabled={selectedRows.size === 0 || loading}
            style={{
              padding: '6px 12px',
              backgroundColor: '#dc3545',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: selectedRows.size === 0 || loading ? 'not-allowed' : 'pointer',
              fontSize: '12px'
            }}
          >
            删除选中记录 ({selectedRows.size})
          </button>
        </div>
        <table style={{ borderCollapse: 'collapse', width: '100%' }}>
          <thead>
            <tr>
              <th style={{ 
                border: '1px solid #ddd', 
                padding: '8px', 
                backgroundColor: '#f2f2f2',
                textAlign: 'left',
                width: '40px'
              }}>
                <input
                  type="checkbox"
                  onChange={(e) => {
                    if (e.target.checked) {
                      // 选择所有行
                      const allIds = tableData.map(row => row.id || row.ID);
                      setSelectedRows(new Set(allIds));
                    } else {
                      // 取消选择所有行
                      setSelectedRows(new Set());
                    }
                  }}
                  checked={selectedRows.size === tableData.length && tableData.length > 0}
                />
              </th>
              {columns.map((col) => (
                <th 
                  key={col} 
                  style={{ 
                    border: '1px solid #ddd', 
                    padding: '8px', 
                    backgroundColor: '#f2f2f2',
                    textAlign: 'left'
                  }}
                >
                  {col}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {tableData.map((row, index) => (
              <tr 
                key={row.id || row.ID || index}
                style={{
                  backgroundColor: selectedRows.has(row.id || row.ID) ? '#e6f3ff' : (index % 2 === 0 ? '#fff' : '#f9f9f9')
                }}
              >
                <td style={{ 
                  border: '1px solid #ddd', 
                  padding: '8px' 
                }}>
                  <input
                    type="checkbox"
                    checked={selectedRows.has(row.id || row.ID)}
                    onChange={(e) => {
                      const newSelectedRows = new Set(selectedRows);
                      if (e.target.checked) {
                        newSelectedRows.add(row.id || row.ID);
                      } else {
                        newSelectedRows.delete(row.id || row.ID);
                      }
                      setSelectedRows(newSelectedRows);
                    }}
                  />
                </td>
                {columns.map((col) => (
                  <td 
                    key={col} 
                    style={{ 
                      border: '1px solid #ddd', 
                      padding: '8px' 
                    }}
                  >
                    {col.includes('created_at') || col.includes('updated_at') || col.includes('changed_at') || col.includes('timestamp') ?
                      formatToBeijingTime(row[col]) :
                      (row[col] !== undefined && row[col] !== null ? 
                        (typeof row[col] === 'object' ? JSON.stringify(row[col]) : String(row[col])) : 
                        '')
                    }
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
        <p>总共 {tableData.length} 条记录</p>
      </div>
    );
  };

  // 新增：渲染无货货位表格
  const renderEmptySlotsTable = () => {
    if (emptySlotsData.length === 0) return null;

    // 检查数据是否存在
    if (!emptySlotsData[0]) return null;

    // 获取列名
    const columns = Object.keys(emptySlotsData[0]);

    return (
      <div style={{ marginTop: '20px' }}>
        <h3>无货货位数据:</h3>
        <table style={{ borderCollapse: 'collapse', width: '100%' }}>
          <thead>
            <tr>
              {columns.map((col) => (
                <th 
                  key={col} 
                  style={{ 
                    border: '1px solid #ddd', 
                    padding: '8px', 
                    backgroundColor: '#f2f2f2',
                    textAlign: 'left'
                  }}
                >
                  {col}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {emptySlotsData.map((row, index) => (
              <tr key={index}>
                {columns.map((col) => (
                  <td 
                    key={col} 
                    style={{ 
                      border: '1px solid #ddd', 
                      padding: '8px' 
                    }}
                  >
                    {col.includes('created_at') || col.includes('updated_at') || col.includes('changed_at') || col.includes('timestamp') ?
                      formatToBeijingTime(row[col]) :
                      (row[col] !== undefined && row[col] !== null ? 
                        (typeof row[col] === 'object' ? JSON.stringify(row[col]) : String(row[col])) : 
                        '')
                    }
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
        <p>总共 {emptySlotsData.length} 条无货货位记录</p>
      </div>
    );
  };

  // 新增：渲染未下发任务表格
  const renderUnissuedTasksTable = () => {
    if (unissuedTasksData.length === 0) return null;

    // 检查数据是否存在
    if (!unissuedTasksData[0]) return null;

    // 获取列名
    const columns = Object.keys(unissuedTasksData[0]);

    return (
      <div style={{ marginTop: '20px' }}>
        <h3>未下发任务数据:</h3>
        <table style={{ borderCollapse: 'collapse', width: '100%' }}>
          <thead>
            <tr>
              {columns.map((col) => (
                <th 
                  key={col} 
                  style={{ 
                    border: '1px solid #ddd', 
                    padding: '8px', 
                    backgroundColor: '#f2f2f2',
                    textAlign: 'left'
                  }}
                >
                  {col}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {unissuedTasksData.map((row, index) => (
              <tr key={index}>
                {columns.map((col) => (
                  <td 
                    key={col} 
                    style={{ 
                      border: '1px solid #ddd', 
                      padding: '8px' 
                    }}
                  >
                    {col.includes('created_at') || col.includes('updated_at') || col.includes('changed_at') || col.includes('timestamp') ?
                      formatToBeijingTime(row[col]) :
                      (row[col] !== undefined && row[col] !== null ? 
                        (typeof row[col] === 'object' ? JSON.stringify(row[col]) : String(row[col])) : 
                        '')
                    }
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
        <p>总共 {unissuedTasksData.length} 条未下发任务记录</p>
      </div>
    );
  };

  return (
    <div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
      <h2>数据库调试页面</h2>
      
      {/* 表查询 */}
      <div style={{ marginBottom: '20px', padding: '15px', border: '1px solid #ddd', borderRadius: '5px' }}>
        <h3>表数据查询</h3>
        <div style={{ display: 'flex', gap: '10px', alignItems: 'center', marginBottom: '10px' }}>
          {/* 修改：将输入框替换为下拉选择框 */}
          <select
            value={tableName}
            onChange={(e) => setTableName(e.target.value)}
            style={{ 
              padding: '8px', 
              border: '1px solid #ddd', 
              borderRadius: '4px',
              flex: 1,
              maxWidth: '400px'
            }}
          >
            {tableOptions.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          <button
            onClick={fetchTableData}
            disabled={loading}
            style={{
              padding: '8px 16px',
              backgroundColor: '#007bff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: loading ? 'not-allowed' : 'pointer'
            }}
          >
            {loading ? '查询中...' : '查询'}
          </button>
        </div>
        
        {error && (
          <div style={{ 
            color: 'red', 
            marginBottom: '20px', 
            padding: '10px', 
            backgroundColor: '#ffe6e6',
            border: '1px solid #ff0000',
            borderRadius: '4px'
          }}>
            <strong>错误:</strong> {error}
          </div>
        )}

        {renderTableData()}
      </div>

      {/* 新增：无货货位查询 */}
      <div style={{ marginBottom: '20px', padding: '15px', border: '1px solid #ddd', borderRadius: '5px' }}>
        <h3>无货货位查询</h3>
        <div style={{ marginBottom: '10px' }}>
          <button
            onClick={fetchEmptySlots}
            disabled={emptySlotsLoading}
            style={{
              padding: '8px 16px',
              backgroundColor: '#17a2b8',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: emptySlotsLoading ? 'not-allowed' : 'pointer'
            }}
          >
            {emptySlotsLoading ? '查询中...' : '查询无货货位'}
          </button>
        </div>

        {emptySlotsError && (
          <div style={{ 
            color: 'red', 
            marginBottom: '20px', 
            padding: '10px', 
            backgroundColor: '#ffe6e6',
            border: '1px solid #ff0000',
            borderRadius: '4px'
          }}>
            <strong>错误:</strong> {emptySlotsError}
          </div>
        )}

        {renderEmptySlotsTable()}
      </div>

      {/* 新增：未下发任务查询 */}
      <div style={{ marginBottom: '20px', padding: '15px', border: '1px solid #ddd', borderRadius: '5px' }}>
        <h3>未下发任务查询</h3>
        <p>查询条件：is_issued = 0（未下发的任务）</p>
        <p>提示：只会查询TaskList表中is_issued字段值为0的任务记录</p>
        <div style={{ marginBottom: '10px' }}>
          <button
            onClick={fetchUnissuedTasks}
            disabled={unissuedTasksLoading}
            style={{
              padding: '8px 16px',
              backgroundColor: '#ffc107',
              color: 'black',
              border: 'none',
              borderRadius: '4px',
              cursor: unissuedTasksLoading ? 'not-allowed' : 'pointer'
            }}
          >
            {unissuedTasksLoading ? '查询中...' : '查询未下发任务'}
          </button>
        </div>

        {unissuedTasksError && (
          <div style={{ 
            color: 'red', 
            marginBottom: '20px', 
            padding: '10px', 
            backgroundColor: '#ffe6e6',
            border: '1px solid #ff0000',
            borderRadius: '4px'
          }}>
            <strong>错误:</strong> {unissuedTasksError}
          </div>
        )}

        {renderUnissuedTasksTable()}
      </div>

      {/* 修改：查询无货货位（仅查询） */}
      <div style={{ marginBottom: '20px', padding: '15px', border: '1px solid #ddd', borderRadius: '5px', backgroundColor: '#f8f9fa' }}>
        <h3>查询无货货位</h3>
        <p>功能说明：每次点击只查询一个无货货位：</p>
        <ul>
         
          <ul>
            <li>无记录 → 返回该货位信息</li>
            <li>已下发记录（is_issued = 1）→ 返回该货位信息（历史任务）</li>
            <li>未下发记录（is_issued = 0）→ 跳过，继续查找下一个货位</li>
          </ul>
          <li>找到第一个可插入的货位后立即返回结果</li>
        </ul>
        <div style={{ marginBottom: '10px' }}>
          <button
            onClick={autoQueryEmptySlots}
            disabled={autoInsertLoading}
            style={{
              padding: '8px 16px',
              backgroundColor: '#28a745',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: autoInsertLoading ? 'not-allowed' : 'pointer'
            }}
          >
            {autoInsertLoading ? '查询中...' : '查询任务货位'}
          </button>
        </div>

        {autoInsertResult && (
          <div style={{ 
            color: 'green', 
            marginBottom: '20px', 
            padding: '10px', 
            backgroundColor: '#d4edda',
            border: '1px solid #c3e6cb',
            borderRadius: '4px'
          }}>
            <strong>查询结果:</strong> {autoInsertResult.message}
            {autoInsertResult.foundSlot && (
              <div style={{ marginTop: '10px' }}>
                <strong>找到的货位:</strong> 排{autoInsertResult.foundSlot.row}, 列{autoInsertResult.foundSlot.column}, 层{autoInsertResult.foundSlot.layer}
              </div>
            )}
          </div>
        )}

        {autoInsertError && (
          <div style={{ 
            color: 'red', 
            marginBottom: '20px', 
            padding: '10px', 
            backgroundColor: '#ffe6e6',
            border: '1px solid #ff0000',
            borderRadius: '4px'
          }}>
            <strong>错误:</strong> {autoInsertError}
          </div>
        )}
      </div>
    </div>
  );
};

export default DatabaseDebugPage;